<template>
    <div class="addMessagePost">
        <el-form class="form" ref="form" :model="formData" :rules="rules" label-width="200px">
            <el-form-item label="投递任务名称" prop="name">
                <el-input size="small" v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="投递类型">
                <el-select v-model="formData.type" size="small">
                    <el-option label="邮件" :value="1"></el-option>
                    <el-option label="短信" :value="2"></el-option>
                    <el-option label="邮短" :value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="投递环境">
                <el-select v-model="formData.env" size="small">
                    <el-option label="测试环境" value="test"></el-option>
                    <el-option label="正式环境" value="prod"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="邮件模板标识" v-if="formData.type===1||formData.type===3" prop="emailTemplateCode">
                <el-input size="small" v-model="formData.emailTemplateCode"></el-input>
            </el-form-item>
            <el-form-item label="短信模板标识" v-if="formData.type===2||formData.type===3" prop="smsTemplateCode">
                <el-input size="small" v-model="formData.smsTemplateCode"></el-input>
            </el-form-item>
            <template v-if="formData.type===1||formData.type===3">
                <el-form-item label="投递用户">
                    <el-upload class="upload"
                               ref="targetUpload"
                               action=""
                               :on-change="onTargetFileChange"
                               :file-list="target.fileList"
                               :show-file-list="false"
                               :auto-upload="false">
                        <el-input slot="trigger" class="fileName" :class="target.fileList[0]?'hasFile':'noFile'"
                                  v-model="target.fileName" size="small" placeholder="请选择文件"></el-input>
                        <el-button size="small"
                                   :loading="target.loading"
                                   :disabled="target.fileList.length===0"
                                   :type="target.fileList.length===0?'info':'success'"
                                   @click="targetUpload">导入
                        </el-button>
                    </el-upload>
                    <el-button type="primary" size="small" @click="downloadTemplate">下载模板文件</el-button>
                </el-form-item>
                <el-form-item label="投递设置">
                    <el-radio-group v-model="formData.postType" size="small">
                        <el-radio :label="1">实时发送</el-radio>
                        <el-radio :label="2">定时发送</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="投递时间" v-if="formData.postType===2">
                    <el-date-picker
                        v-model="formData.time"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="短信投递内容" v-if="formData.type!==1">
                    <el-input size="small" v-model="formData.sms.text"></el-input>
                </el-form-item>
                <el-form-item label="邮件内容（图片）" v-if="formData.type!==2">
                    <!-- <el-input type="textarea" :autosize="{ minRows: 6}" placeholder="请输入邮件内容" v-model="formData.email.text"></el-input> -->
                    <el-upload class="upload"
                               ref="emailUpload"
                               action=""
                               :on-change="onEmailFileChange"
                               :file-list="email.fileList"
                               :show-file-list="false"
                               :auto-upload="false">
                        <el-input slot="trigger" class="fileName" :class="email.fileList[0]?'hasFile':'noFile'"
                                  v-model="email.fileName" size="small" placeholder="请选择文件"></el-input>
                        <el-button size="small"
                                   :loading="email.loading"
                                   :disabled="email.fileList.length===0"
                                   :type="email.fileList.length===0?'info':'success'"
                                   @click="emailUpload">上传
                        </el-button>
                    </el-upload>
                    <el-row v-if="formData.email.img" class="show-image">
                        <img alt="image" :src="formData.email.img"/>
                    </el-row>
                </el-form-item>
                <el-form-item label="邮件跳转链接" v-if="formData.type!==2">
                    <el-input size="small" v-model="formData.email.url"></el-input>
                </el-form-item>
                <el-form-item class="operation">
                    <el-button @click="closeTab">取 消</el-button>
                    <el-button type="primary" @click="ok" :loading="formData.loading">投 递</el-button>
                </el-form-item>
            </template>
            <template v-else>
                <h3 style="text-align: center;margin-top: 200px">暂不支持</h3>
            </template>
        </el-form>
    </div>
</template>

<script>
    export default {
        name: "addMessagePost",
        data() {
            return {
                formData: {
                    name: '',
                    type: 3,
                    postType: 1,
                    emailTemplateCode: '',
                    smsTemplateCode: '',
                    time: '',
                    email: {
                        // text: '',
                        url: '',
                        img: ''
                    },
                    sms: {
                        text: ''
                    },
                    emailContent: '',
                    smsContent: '',
                    env: 'test',
                    target: [],
                    loading: false
                },
                target: {
                    fileList: [],
                    fileName: '',
                    loading: false
                },
                email: {
                    fileList: [],
                    fileName: '',
                    loading: false
                },
                rules: {
                    name: [{required: true, message: '请输入任务名称', trigger: 'blur'},],
                    emailTemplateCode: [{required: true, message: '请输入邮件模板标识', trigger: 'blur'},],
                    smsTemplateCode: [{required: true, message: '请输入短信模板标识', trigger: 'blur'},],
                },
            }
        },
        methods: {
            ok() {
                let _this = this;
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        _this.formData.emailContent = JSON.stringify({
                            content: _this.createHtml(_this.formData.email)
                        });
                        _this.formData.smsContent = JSON.stringify({
                            content: _this.formData.sms.text
                        });
                        _this.formData.loading = true;
                        _this.axios({
                            method: 'post',
                            url: '/activityConsole/messagePost/send',
                            data: _this.formData
                        }).then(res => {
                            console.log(res.data);
                            if (res.data.status === '200') {
                                _this.$message.success('保存成功');
                            } else {
                                _this.$message.warning(res.data.description);
                            }
                            _this.formData.loading = false;
                            this.closeTab();
                        }).catch(e => {
                            console.log(e);
                            _this.formData.loading = false;
                        });
                    } else {

                    }
                });
            },
            closeTab() {
                this.$store.dispatch('delVisitedViews', this.$route);
                this.$router.push({path: 'messagePostList'})
            },
            onTargetFileChange(file) {
                this.target.fileList = [file];
                this.target.fileName = file.name;
            },
            onEmailFileChange(file) {
                this.email.fileList = [file];
                this.email.fileName = file.name;
            },
            targetUpload() {
                let _this = this;
                _this.target.loading = true;
                let data = new FormData();
                data.append('file', _this.target.fileList[0].raw);
                _this.axios({
                    method: 'post',
                    url: '/activityConsole/messagePost/importTargetList',
                    data: data
                }).then(res => {
                    if (res.data.status === '200') {
                        _this.formData.target = res.data.data;
                        _this.target.fileList = [];
                        _this.target.fileName = '已上传';
                        _this.$message.success(`解析完成，共得到${res.data.data.length}条数据`);
                    } else {
                        _this.$message.warning('文件解析失败，请检查文件格式或稍后再试');
                    }
                    _this.target.loading = false;
                }).catch(e => {
                    console.log(e);
                    _this.target.loading = false;
                });
            },
            emailUpload() {
                let _this = this;
                _this.email.loading = true;
                let data = new FormData();
                data.append('file', _this.email.fileList[0].raw);
                _this.axios({
                    method: 'post',
                    url: '/activityConsole/messagePost/imageUpload',
                    data: data
                }).then(res => {
                    if (res.data.status === '200') {
                        _this.formData.email.img = res.data.data;
                        _this.email.fileList = [];
                        _this.email.fileName = '已上传';
                        _this.$message.success(`上传完成`);
                    } else {
                        _this.$message.warning('文件上传失败');
                    }
                    _this.email.loading = false;
                }).catch(e => {
                    console.log(e);
                    _this.email.loading = false;
                });
            },
            downloadTemplate() {
                location.href = '/activityConsole/messagePost/downloadTemplate?type=' + this.formData.type
            },
            createHtml(email) {
                return `
                    <div style="width: 100%;text-align: center;">
                        <a href="${email.url}">
                            <img src="${email.img}" style="width: 100%" alt="活动营销平台"/>
                        </a>
                    </div>
                `;
            }
        }
    }
</script>

<style lang="scss" scoped>
    .addMessagePost {
        .form {
            margin: 30px 30px 0;
            .upload {
                display: inline-block;
                .fileName {
                    width: 300px;
                }
            }
            .el-button {
                margin-left: 5px;
                padding: 8px 20px;
            }
            .operation {
                display: flex;
                justify-content: left;
                .el-button {
                    padding: 10px 20px;
                    margin: 0 20px;
                }
            }
            .show-image {
                img {
                    max-width: 600px;
                    max-height: 300px;
                    margin-top: 5px;
                }
            }
        }
    }
</style>
